import { useRouter } from "vue-router";
import axios from "axios";
import { reactive } from "vue";

//1.创建axios的实例
const instance = axios.create({
    baseURL: '',
    timeout: 15000,//15秒超时，更合理的超时时间
    // headers: {'X-Custom-Header': 'foobar'}
  });

//拦截器 
//2.添加请求拦截器 请求接口之前做一些操作  加上token
instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
)
//3.添加响应拦截器 响应回来 做一些处理
instance.interceptors.response.use(
  response => {
    return response.data;
  },
  error=>{ 
     //实现Token自动刷新
      const router = useRouter();
      if(error.response && error.response.status ===401)
      {
        //收到401错误，尝试刷新Token
        //获取当前的Token以及刷新Token
          const refreshToken = localStorage.getItem("refreshToken");
          
          if(!refreshToken) {
            //没有刷新Token，跳转到登录页
            router.push({path:"/"});
            return Promise.reject(error);
          }
          //
          const tokens = {
            accessToken: localStorage.getItem("token"),
            refreshToken: refreshToken
          };
          //尝试刷新Token:
          return axios.post("http://localhost:5145/api/Login/Refresh", tokens)
          .then(res=>{
            console.log("Token刷新成功:", res.data);
            //更新Token
            localStorage.setItem("token", res.data.data.accessToken);
            localStorage.setItem("refreshToken", res.data.data.refreshToken);
            error.config.headers['Authorization'] = "Bearer " + res.data.data.accessToken;
            console.clear();
            return instance(error.config);
          })
          .catch(() => {
            localStorage.removeItem("token");
            localStorage.removeItem("refreshToken");
            router.push({ path: "/" });
            return Promise.reject(error);
          })
          .finally(()=>{
            
          })
      }
      // 对于其他错误，直接抛出
      return Promise.reject(error);
  }
)
//对外暴露一个实例
// export default instance;
export const http=(method='',url='',data={},params={},headers={})=> {
  return instance({method,url,data,params,headers})
}